package chap_01_CompletableFuture.step_02_CompletableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Description 常用API汇总：对计算结果进行合并
 * @Author shihan
 * @Date 2022/9/4 17:30
 * @Version 1.0
 */
public class CompletableStudy_04_API_05 {

    public static void main(String[] args) {
        long t1 = System.currentTimeMillis();

        CompletableFuture<Integer> p1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 10;
        });

        CompletableFuture<Integer> p2 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 20;
        });

        // 将两个异步任务的运行结果进行合并处理，如果一个异步任务执行完了，需要等另外一个异步任务也执行完，才能进行结果合并操作
        // 第二个入参是 BiFunction 接口，接收两个参数，分别是两个异步任务的执行结果返回值
        CompletableFuture<Integer> thenCombine = p1.thenCombine(p2, (res1, res2) -> {
            System.out.println("将两个运行结果进行合并处理...");
            return res1 + res2;
        });

        System.out.println(thenCombine.join());
        long t2 = System.currentTimeMillis();
        System.out.println("耗时：" + (t2 - t1));
    }

}
